import subprocess
import json
import os
from tempfile import TemporaryDirectory

def get_target_dependencies(target_path):
    """使用pipreqs获取目标脚本的真实依赖"""
    with TemporaryDirectory() as tmpdir:
        # 生成requirements.txt到临时目录
        subprocess.run([
            'pipreqs', 
            '--savepath', os.path.join(tmpdir, 'requirements.txt'),
            '--encoding', 'utf8',
            os.path.dirname(target_path)
        ], check=True, capture_output=True)
        
        # 读取并解析依赖包名
        with open(os.path.join(tmpdir, 'requirements.txt')) as f:
            return [line.split('==')[0].strip().lower() for line in f]

def filter_licenses(target_packages):
    """过滤pip-licenses输出的许可证信息"""
    result = subprocess.run(
        ['pip-licenses', '--format', 'json','--with-urls','--with-authors'],
        capture_output=True, 
        text=True,
        check=True
    )
    all_licenses = json.loads(result.stdout)
    
    # 转换为小写比较以处理大小写差异
    target_set = {pkg.lower() for pkg in target_packages}
    return [
        pkg for pkg in all_licenses 
        if pkg['Name'].lower() in target_set
    ]

if __name__ == '__main__':
    target_script = r'/.../xxx/PackageAnalyzer.py'  # 修改为目标脚本路径
    
    # 步骤1：获取目标依赖
    try:
        deps = get_target_dependencies(target_script)
    except subprocess.CalledProcessError as e:
        print(f"pipreqs错误: {e.stderr}")
        exit(1)
    
    # 步骤2：过滤许可证信息
    try:
        filtered = filter_licenses(deps)
        print(json.dumps(filtered, indent=2, ensure_ascii=False))
    except subprocess.CalledProcessError as e:
        print(f"pip-licenses错误: {e.stderr}")
        exit(1)